import os
import pandas as pd
import re
from check.check1 import check_leading_trailing
from utils.utils2 import *


def process_to_csv(read_path, save_path):
    file_list = ["n642415", "naca23015", "naca23018", "naca2412",
                 "naca1.dat", "e664ex", "lrn1007", "naca64a010",
                 "s1221", "sc1095r8"]
    for file in file_list:
        if file in read_path:
            print("remove: ", read_path)
            return
    file = open(read_path, mode='r')
    strs = file.readlines()
    dict = {}
    x = []
    y = []

    for tmp_str in strs:
        if tmp_str == "":
            continue
        tmp_str = tmp_str.strip()
        while "  " in tmp_str:
            tmp_str = tmp_str.replace("  ", " ")
        tmp_strs = tmp_str.split(" ")
        if "	" in tmp_str:
            tmp_strs = tmp_str.split("	")
        if re.match(r"^([-,0-9]{0,}[.][0-9]*)$", tmp_strs[0]) == None:
            continue
        if re.match(r"^([-,0-9]{0,}[.][0-9]*)$", tmp_strs[1]) == None:
            continue
        if float(tmp_strs[1]) > 10:
            continue
        x.append(float(tmp_strs[0]))
        y.append(float(tmp_strs[1]))

    df = pd.DataFrame(dict)
    df['x'] = x
    df['y'] = y
    df.to_csv(save_path, index=False)


def file_rename(file_name):
    os.rename(file_name, file_name[:-3] + "dat")


def csv_out_range(file_path):
    df = pd.read_csv(file_path)
    epsilon = 1e-5
    list_x = df['x']
    for i, j in enumerate(list_x):
        if j > 1 - epsilon and j < 1 + epsilon:
            list_x[i] = 1
            print(file_path, i, j)
        elif j < epsilon and j > -epsilon:
            list_x[i] = 0
            print(file_path, i, j)
    df.to_csv(file_path, index=False)
    print()

def loop_dataset_process_leading(read_dir, save_dir):
    for file in os.listdir(read_dir):
        file_path = os.path.join(read_dir, file)
        save_path = os.path.join(save_dir, file)
        ordinates = pd.read_csv(file_path).to_numpy()
        leading, trailing = check_leading_trailing(file_path)
        _, _, _, x_leading, y_leading, id_leading = leading
        _, _, _, x_trailing, y_trailing, id_trailing = trailing
        if x_leading.shape[0] == 2:
            if x_leading.all() == 0:
                y_max = np.argmax(y_leading)
                y_min = np.argmin(y_leading)
                ordinates = np.concatenate([ordinates[0:id_leading[0]],
                                            np.expand_dims(ordinates[id_leading[y_min]], axis=0),
                                            ordinates[(id_leading[1] + 1):]], axis=0)
            else:
                ordinates = move_x(ordinates, -x_leading[0])
        else:
            ordinates = move_x(ordinates, -x_leading[0])
        if id_leading.shape[0] == 1 and ordinates[id_leading[0]][1] != 0:
            ordinates = move_y(ordinates, -ordinates[id_leading[0]][1])
        elif id_leading.shape[0] == 2 and ordinates[id_leading][1].any() != 0:
            ordinates[0:id_leading[0] + 1] = move_y(ordinates[0:id_leading[0] + 1], -ordinates[id_leading[0]][1])
            ordinates[id_leading[1]::] = move_y(ordinates[id_leading[1]::], -ordinates[id_leading[1]][1])
        def fmin(x):
            return np.argwhere(x == np.min(x)).flatten()

        id_leading = fmin(ordinates[:, 0])
        if id_leading.shape[0] == 2:
            ordinates = np.delete(ordinates, id_leading[0], axis=0)

        df = pd.DataFrame(ordinates)
        df.columns = ["x", "y"]
        df.to_csv(save_path, index=False)


def loop_dataset_process_trailing(read_dir, save_dir):
    for file in os.listdir(read_dir):
        file_path = os.path.join(read_dir, file)
        save_path = os.path.join(save_dir, file)
        ordinates = pd.read_csv(file_path).to_numpy()
        leading, trailing = check_leading_trailing(file_path)
        _, _, _, x_leading, y_leading, id_leading = leading
        _, _, _, x_trailing, y_trailing, id_trailing = trailing
        assert id_leading.shape[0] == 1

        def fmax(x):
            return np.argwhere(x == np.max(x)).flatten()

        id_trailing1 = fmax(ordinates[0:id_leading[0], 0])
        id_trailing2 = fmax(ordinates[id_leading[0]::, 0]) + id_leading[0]
        ordinates[0:id_leading[0]] = rotate(ordinates[0:id_leading[0]], ordinates[id_trailing1[0]])
        ordinates[id_leading[0]::] = rotate(ordinates[id_leading[0]::], ordinates[id_trailing2[0]])
        x = ordinates[0:id_leading[0] + 1, 0]
        x_min = np.min(x)
        x_max = np.max(x)
        x = (x - x_min) / (x_max - x_min)
        ordinates[0:id_leading[0] + 1, 0] = x
        x = ordinates[id_leading[0]::, 0]
        x_min = np.min(x)
        x_max = np.max(x)
        x = (x - x_min) / (x_max - x_min)
        ordinates[id_leading[0]::, 0] = x

        df = pd.DataFrame(ordinates)
        df.columns = ["x", "y"]
        df.to_csv(save_path, index=False)
